﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EngineOfEvermore.Scene;
using System.Diagnostics;
using EngineOfEvermore.Common;
using EngineOfEvermore.Scene.Visual;
using EngineOfEvermore.Imaging;

namespace EngineOfEvermore.Editor.Common
{
    public partial class SceneView : UserControl
    {
        class MouseEventHandler
        {
            enum State
            { 
                Idle,
                Moving
            };

            readonly SceneView _owner;
            State _state;
            Vector2d _lastMousePosition;

            public bool IsSubscribedToMouseEvents
            {
                get;
                private set;
            }

            public MouseEventHandler( SceneView owner )
            {
                _owner = owner;
            }

            public void SubscribeToMouseEvents()
            {
                if ( !this.IsSubscribedToMouseEvents )
                {
                    _owner.MouseDown += _owner_MouseDown;
                    _owner.MouseUp += _owner_MouseUp;
                    _owner.MouseMove += _owner_MouseMove;
                    _owner.MouseWheel += _owner_MouseWheel;

                    this.IsSubscribedToMouseEvents = true;
                }
            }

            public void UnsubscribeFromMouseEvents()
            {
                if ( this.IsSubscribedToMouseEvents )
                {
                    _owner.MouseDown -= _owner_MouseDown;
                    _owner.MouseUp -= _owner_MouseUp;
                    _owner.MouseMove -= _owner_MouseMove;
                    _owner.MouseWheel -= _owner_MouseWheel;

                    this.IsSubscribedToMouseEvents = false;
                }
            }

            void _owner_MouseWheel( object sender, MouseEventArgs e )
            {
                if ( e.Delta > 0 )
                {
                    _owner.Camera.Scale *= 1.1f;
                }
                else
                {
                    _owner.Camera.Scale /= 1.1f;
                }
            }

            void _owner_MouseMove( object sender, MouseEventArgs e )
            {
                if ( _state == State.Moving )
                {
                    Vector2d currentPosition = new Vector2d( e.X, e.Y );
                    Vector2d diff = currentPosition - _lastMousePosition;

                    diff /= _owner.Camera.Scale;

                    _owner.Camera.Position -= diff;

                    _lastMousePosition = currentPosition;
                }
            }

            void _owner_MouseUp( object sender, MouseEventArgs e )
            {
                if ( _state == State.Moving )
                {
                    _state = State.Idle;
                }
            }

            void _owner_MouseDown( object sender, MouseEventArgs e )
            {
                if ( e.Button == MouseButtons.Right )
                {
                    _state = State.Moving;
                    _lastMousePosition = new Vector2d( e.X, e.Y );
                }
            }
        }

        AgateLib.DisplayLib.DisplayWindow _displayWindow;
        SceneGraph _sceneGraph;
        bool _initialized;
        bool _doRender = true;
        bool _clearBeforeDrawing = true;
        Camera _camera = GraphicsImplementation.Instance.CreateCamera();
        MouseEventHandler _mouseEventHandler;
        bool _enableMouseCameraControl = true;
        IRenderer _renderer;

        public SceneView()
        {
            InitializeComponent();

            _mouseEventHandler = new MouseEventHandler( this );
            _mouseEventHandler.SubscribeToMouseEvents();
        }

        public void Initialize()
        {
            AgateLib.DisplayLib.CreateWindowParams createParams =
                AgateLib.DisplayLib.CreateWindowParams.FromControl( this );

            _displayWindow = new AgateLib.DisplayLib.DisplayWindow( createParams );
            _renderer = // new AgateRenderer( _camera );
                GraphicsImplementation.Instance.CreateRenderer( _camera );

            if ( _doRender )
            {
                AgateLib.Core.KeepAliveEvent += _render;
            }

            _camera.ViewportSize = this.ClientSize;

            _initialized = true;
        }

        public void Redraw()
        {
            _render();
        }

        public SceneGraph SceneGraph
        {
            get { return _sceneGraph; }
            set { _sceneGraph = value; }
        }

        public Camera Camera
        {
            get { return _camera; }
        }

        [DefaultValue( true )]
        [Category( "SceneView" )]
        public bool DoRender
        {
            get 
            { 
                return _doRender;
            }
            set 
            {
                if ( _doRender != value )
                {
                    _doRender = value;

                    if ( _initialized )
                    {
                        if ( _doRender )
                        {
                            AgateLib.Core.KeepAliveEvent += _render;
                        }
                        else
                        {
                            AgateLib.Core.KeepAliveEvent -= _render;
                        }
                    }
                }
            }
        }

        [DefaultValue( true )]
        [Category( "SceneView" )]
        public bool ClearBeforeDrawing
        {
            get { return _clearBeforeDrawing; }
            set { _clearBeforeDrawing = value; }
        }

        [DefaultValue( true )]
        public bool EnableMouseCameraControl
        {
            get { return _enableMouseCameraControl; }
            set
            {
                _enableMouseCameraControl = value;

                if ( _enableMouseCameraControl )
                {
                    _mouseEventHandler.SubscribeToMouseEvents();
                }
                else
                {
                    _mouseEventHandler.UnsubscribeFromMouseEvents();
                }
            }
        }

        void _render()
        {
            Debug.Assert( _initialized );
            Debug.Assert( _displayWindow != null );

            if ( !_clearBeforeDrawing && _sceneGraph == null )
            {
                return;
            }

            AgateLib.DisplayLib.Display.RenderTarget = _displayWindow;

            AgateLib.DisplayLib.Display.BeginFrame();
            
            if ( _clearBeforeDrawing )
            {
                AgateLib.DisplayLib.Display.Clear();
            }

            if ( _sceneGraph != null )
            {
                _camera.ApplyTransform(); 
                _sceneGraph.Draw( _camera.GetDisplayedArea() , _renderer );
            }

            AgateLib.DisplayLib.Display.EndFrame();
        }

        void _clientSizeChanged( object sender, EventArgs e )
        {
            _camera.ViewportSize = this.ClientSize;
        }
    }
}
